﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LJSheng.Web.live
{
    public partial class zb : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["sn"]))
            {
                zhuce.Visible = true;
                SNTB.Visible = true;
            }
        }

        private string Encrypt(string encryptString, string encryptKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            des.Mode = System.Security.Cryptography.CipherMode.ECB;
            byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(encryptString);
            //建立加密对象的密钥和偏移量   
            //原文使用ASCIIEncoding.ASCII方法的GetBytes方法   
            //使得输入密码必须输入英文文本   
            des.Key = ASCIIEncoding.ASCII.GetBytes(encryptKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(encryptKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

        protected void zhuce_Click(object sender, EventArgs e)
        {
            try
            {
                string diskid = SNTB.Text.Trim();
                StringBuilder sb = new StringBuilder();
                if (lmcb.Checked)
                {
                    sb.Append("1");
                }
                else
                {
                    sb.Append("0");
                }
                if (zjcb.Checked)
                {
                    sb.Append("1");
                }
                else
                {
                    sb.Append("0");
                }
                if (phbcb.Checked)
                {
                    sb.Append("1");
                }
                else
                {
                    sb.Append("0");
                }
                if (cjcb.Checked)
                {
                    sb.Append("1");
                }
                else
                {
                    sb.Append("0");
                }
                if (xqcb.Checked)
                {
                    sb.Append("1");
                }
                else
                {
                    sb.Append("0");
                }
                if (pkcb.Checked)
                {
                    sb.Append("1");
                }
                else
                {
                    sb.Append("0");
                }
                if (xqpkcb.Checked)
                {
                    sb.Append("1");
                }
                else
                {
                    sb.Append("0");
                }
                if (spxqcb.Checked)
                {
                    sb.Append("1");
                }
                else
                {
                    sb.Append("0");
                }
                sb.Append("0000000000");
                string czk = RQTB.Text.Trim() + MBTB.Text.Trim().ToUpper();
                string xq = Encrypt(sb.ToString() + diskid, "ljsheng1");
                string cz = MMCB.Checked ? Encrypt(czk + diskid, "ljsheng1") : res(czk + diskid);
                //陌陌
                if (sb.ToString().Contains("1"))
                {
                    AddSQ(diskid, xq);
                }
                else
                {
                    xq = "";
                }
                //充值卡
                if (string.IsNullOrEmpty(czk))
                {
                    cz = "";
                }
                else
                {
                    if (MMCB.Checked)
                    {
                        AddSQ(czk.Substring(10, 2) + diskid, cz);
                    }
                    else
                    {
                        AddCZK(diskid, cz);
                    }
                }
                Response.Write(xq + "\r\n" + cz);
            }
            catch { }
        }

        /// <summary>
        /// 旧授权
        /// </summary>
        /// <param name="diskid"></param>
        /// <param name="czk"></param>
        protected void AddSQ(string diskid, string czk)
        {
            string path = System.Web.HttpContext.Current.Server.MapPath("/czk/");
            string filename = path + diskid + ".html";
            if (WLCB.Checked)
            {
                StreamWriter sr = null;
                try
                {
                    if (File.Exists(filename))
                    {
                        File.Delete(filename);
                    }
                    sr = File.CreateText(filename);
                    sr.WriteLine(czk);
                }
                catch
                {
                }
                finally
                {
                    if (sr != null)
                        sr.Close();
                }
            }

            if (SCB.Checked && File.Exists(filename))
            {
                File.Delete(filename);
            }
        }
        /// <summary>
        /// 新版授权
        /// </summary>
        /// <param name="diskid"></param>
        /// <param name="czk"></param>
        protected void AddCZK(string diskid, string czk)
        {
            string path = System.Web.HttpContext.Current.Server.MapPath("/live/");
            string filename = path + diskid + ".html";
            if (WLCB.Checked)
            {
                StreamWriter sr = null;
                try
                {
                    if (File.Exists(filename))
                    {
                        File.Delete(filename);
                    }
                    sr = File.CreateText(filename);

                    //string pkey;
                    //string pubkey;
                    //RSAKey(out pkey, out pubkey);
                    ///充值卡
                    var bb = new
                    {
                        LJSHENG = new { 
                            ks = SNTB.Text.Trim(),
                            name = DZTB.Text.Trim(),
                            QQ= !string.IsNullOrEmpty(DZTB.Text.Trim()) ? "QQ:9021616" : "",
                        },
                        linjiansheng = new {
                            dz = !string.IsNullOrEmpty(DZTB.Text.Trim()) ? res(RQTB.Text.Trim() + "DZ" + diskid) : "",
                            pk = KSCB.Checked? res(RQTB.Text.Trim() + "PK"+ diskid) : "",
                            ks = KSHHCB.Checked ? res(RQTB.Text.Trim() + "KS" + diskid) : "",
                            dh = DYCB.Checked ? res(RQTB.Text.Trim() + "DH" + diskid) : "",
                            dy = DYHHCB.Checked ? res(RQTB.Text.Trim() + "DY" + diskid) : ""
                        },
                        live = new {
                            update=1,
                            bbh=2,
                            key = Encrypt("QQ:9021616", "ljsheng1")
                        },
                        data = new { 
                            time = RQTB.Text,
                            msg = "QQ:9021616"
                        }
                    };
                    czk = JsonConvert.SerializeObject(bb);

                    sr.WriteLine(czk);

                    ///第三方认证
                    string sjc = LJSheng.Common.LCommon.GetTimeStamp(DateTime.Parse(RQTB.Text.Trim()).AddDays(3));
                    int mm = DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour;
                    if (DSFCB.Checked && KSCB.Checked)
                    {
                        POST(URLTB.Text, "{\"reqmaskcode\":\"" + mm.ToString() + "\",\"authmacid\":\"" + SNTB.Text.Trim() + "\",\"expiredtime\":\"" + sjc + "\",\"authchannel\":\"1\"}");
                    }
                    if (DSFCB.Checked && DYCB.Checked)
                    {
                        POST(URLTB.Text, "{\"reqmaskcode\":\"" + mm.ToString() + "\",\"authmacid\":\"" + SNTB.Text.Trim() + "\",\"expiredtime\":\"" + sjc + "\",\"authchannel\":\"2\"}");
                    }
                }
                catch
                {
                }
                finally
                {
                    if (sr != null)
                        sr.Close();
                }
            }

            if (SCB.Checked && File.Exists(filename))
            {
                File.Delete(filename);
            }
        }

        public string res(string es)
        {
            //<RSAKeyValue><Modulus>r8l3eiVWgQLo/kmt1mmMLAT8EUV3vE6TgKxkJV5yq5BvwrOGvpa7EoSSAFHrQsYBoi228TT0riE0mN+P6/gYFuAb1E29GYInbvH+aPouVQdAaNVBmAqmQOM/lAgKGxU6H+PHYtj5YnnmfwJR4jYb0RnmV3u8XSpNKv1KtGt1Ojk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
            LJSheng.Common.RSA rsa = new Common.RSA();
            string pubkey = @"<RSAKeyValue><Modulus>r8l3eiVWgQLo/kmt1mmMLAT8EUV3vE6TgKxkJV5yq5BvwrOGvpa7EoSSAFHrQsYBoi228TT0riE0mN+P6/gYFuAb1E29GYInbvH+aPouVQdAaNVBmAqmQOM/lAgKGxU6H+PHYtj5YnnmfwJR4jYb0RnmV3u8XSpNKv1KtGt1Ojk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
            return rsa.Encrypt(pubkey, es);
        }
        /// <summary>
        /// 产生RSA的密钥
        /// </summary>
        /// <param name="xmlKeys">私钥</param>
        /// <param name="xmlPublicKey">公钥</param>
        public void RSAKey(out string xmlKeys, out string xmlPublicKey)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            xmlKeys = rsa.ToXmlString(true);
            xmlPublicKey = rsa.ToXmlString(false);
        }

        public string POST(string url, string postdata)
        {
            try
            {
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes("");
                HttpWebRequest objWebRequest = (HttpWebRequest)WebRequest.Create(url); //发送地址
                byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(postdata);
                objWebRequest.Method = "POST";//提交方式
                objWebRequest.ContentType = "application/json";
                objWebRequest.ContentLength = requestBytes.Length;
                using (Stream newStream = objWebRequest.GetRequestStream())
                {
                    newStream.Write(requestBytes, 0, requestBytes.Length); //写入参数
                    newStream.Close();
                }
                HttpWebResponse response = (HttpWebResponse)objWebRequest.GetResponse();//获取响应
                StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                return sr.ReadToEnd(); // 返回的数据
            }
            catch (Exception err) { return "http://520299.com"; }
        }

    }
}